home *** CD-ROM | disk | FTP | other *** search
/ HPAVC / HPAVC CD-ROM.iso / GENCTXT.ZIP / CHAP10.TXT < prev    next >
Text File  |  1987-11-21  |  18KB  |  455 lines

  1.  
  2.                        Chapter 10 - File Input/Output
  3.  
  4.  
  5.                               OUTPUT TO A FILE
  6.  
  7.              Load  and  display  the file named FORMOUT.C  for  your
  8.         first example of writing data to a file.  We begin as before
  9.         with the "include" statement for "stdio.h", then define some
  10.         variables for use in the example including a rather  strange
  11.         looking new type.
  12.  
  13.              The  type  "FILE"  is used for a file variable  and  is
  14.         defined in the "stdio.h" file.   It is used to define a file
  15.         pointer  for use in file operations.   The definition  of  C
  16.         contains  the requirement for a pointer to a "FILE",  and as
  17.         usual, the name can be any valid variable name.
  18.  
  19.                                OPENING A FILE
  20.  
  21.              Before we can write to a file,  we must open it.   What
  22.         this  really means is that we must tell the system  that  we
  23.         want  to  write to a file and what the filename is.   We  do
  24.         this with the "fopen" function illustrated in the first line
  25.         of the program.   The file pointer, "fp" in our case, points
  26.         to   the  file  and  two  arguments  are  required  in   the
  27.         parentheses,  the filename first, followed by the file type.
  28.         The filename is any valid DOS filename, and can be expressed
  29.         in  upper  or lower case letters,  or even mixed if  you  so
  30.         desire.   It is enclosed in double quotes.  For this example
  31.         we have chosen the name TENLINES.TXT.   This file should not
  32.         exist  on your disk at this time.   If you have a file  with
  33.         this  name,  you should change its name or move  it  because
  34.         when  we execute this program,  its contents will be erased.
  35.         If you don't have a file by this name,  that is good because
  36.         we will create one and put some data into it.
  37.  
  38.                                READING ("r")
  39.  
  40.              The  second parameter is the file attribute and can  be
  41.         any  of three letters, "r", "w", or "a", and must  be  lower
  42.         case. There are actually additional attributes available  in
  43.         C to allow more flexible I/O.  When an "r" is used, the file
  44.         is  opened for reading, a "w" is used to indicate a file  to
  45.         be used for writing, and an "a" indicates that you desire to
  46.         append  additional data to the data already in  an  existing
  47.         file.   Opening  a file for reading requires that  the  file
  48.         already exist.  If it does not exist, the file pointer  will
  49.         be set to NULL and can be checked by the program.
  50.  
  51.                                WRITING ("w")
  52.  
  53.              When  a file is opened for writing,  it will be created
  54.         if it does not already exist and it will be reset if it does
  55.         resulting in deletion of any data already there.
  56.  
  57.  
  58.                                    Page 70
  59.  
  60.  
  61.  
  62.  
  63.  
  64.  
  65.  
  66.  
  67.  
  68.                        Chapter 10 - File Input/Output
  69.  
  70.  
  71.  
  72.                               APPENDING ("a")
  73.  
  74.              When a file is opened for appending, it will be created
  75.         if it does not already exist and it will be initially empty.
  76.         If  it does exist,  the data input point will be the end  of
  77.         the  present data so that any new data will be added to  any
  78.         data that already exists in the file.
  79.  
  80.                            OUTPUTTING TO THE FILE
  81.  
  82.              The  job of actually outputting to the file  is  nearly
  83.         identical  to  the  outputting we have already done  to  the
  84.         standard output device.   The only real differences are  the
  85.         new  function names and the addition of the file pointer  as
  86.         one  of  the function arguments.   In the  example  program,
  87.         "fprintf" replaces our familiar "printf" function name,  and
  88.         the  file  pointer  defined earlier is  the  first  argument
  89.         within  the  parentheses.   The remainder of  the  statement
  90.         looks  like,  and  in  fact is identical  to,  the  "printf"
  91.         statement.
  92.  
  93.                                CLOSING A FILE
  94.  
  95.              To close a file,  you simply use the function  "fclose"
  96.         with the file pointer in the parentheses.  Actually, in this
  97.         simple  program,  it  is  not necessary to  close  the  file
  98.         because   the  system  will  close  all  open  files  before
  99.         returning to DOS.  It would be good programming practice for
  100.         you to get in the habit of closing all files in spite of the
  101.         fact  that they will be closed automatically,  because  that
  102.         would act as a reminder to you of what files are open at the
  103.         end of each program.
  104.  
  105.              You can open a file for writing,  close it,  and reopen
  106.         it  for  reading,  then  close it,  and open  it  again  for
  107.         appending,  etc.   Each time you open it,  you could use the
  108.         same file pointer,  or you could use a different  one.   The
  109.         file  pointer  is simply a tool that you use to point  to  a
  110.         file and you decide what file it will point to.
  111.  
  112.              Compile  and run this program.   When you run  it,  you
  113.         will  not  get any output to the monitor because it  doesn't
  114.         generate any.   After running it, look at your directory for
  115.         a file named TENLINES.TXT and "type" it.  That is where your
  116.         output will be.   Compare the output with that specified  in
  117.         the program.  It should agree.
  118.  
  119.              Do not erase the file named TENLINES.TXT yet.   We will
  120.         use it in some of the other examples in this chapter.
  121.  
  122.  
  123.  
  124.                                    Page 71
  125.  
  126.  
  127.  
  128.  
  129.  
  130.  
  131.  
  132.  
  133.  
  134.                        Chapter 10 - File Input/Output
  135.  
  136.  
  137.  
  138.                   OUTPUTTING A SINGLE CHARACTER AT A TIME
  139.  
  140.              Load the next example file,  CHAROUT.C,  and display it
  141.         on your monitor.  This program will illustrate how to output
  142.         a single character at a time.
  143.  
  144.              The  program begins with the "include" statement,  then
  145.         defines  some variables including a file pointer.   We  have
  146.         called the file pointer "point" this time, but we could have
  147.         used any other valid variable name.  We then define a string
  148.         of characters to use in the output function using a "strcpy"
  149.         function.   We are ready to open the file for appending  and
  150.         we  do so in the "fopen" function,  except this time we  use
  151.         the  lower cases for the filename.   This is done simply  to
  152.         illustrate  that  DOS  doesn't care about the  case  of  the
  153.         filename.  Notice that the file will be opened for appending
  154.         so  we  will  add  to the lines  inserted  during  the  last
  155.         program.
  156.  
  157.              The  program is actually two nested "for"  loops.   The
  158.         outer  loop  is  simply a count to ten so that  we  will  go
  159.         through the inner loop ten times.   The inner loop calls the
  160.         function  "putc" repeatedly until a character in "others" is
  161.         detected to be a zero.
  162.  
  163.                             THE "putc" FUNCTION
  164.  
  165.              The  part  of the program we are interested in  is  the
  166.         "putc" function.   It outputs one character at a  time,  the
  167.         character  being  the first argument in the parentheses  and
  168.         the  file pointer being the second and last  argument.   Why
  169.         the  designer of C made the pointer first in  the  "fprintf"
  170.         function, and last in the "putc" function is a good question
  171.         for which there may be no answer.   It seems like this would
  172.         have been a good place to have used some consistency.
  173.  
  174.              When  the textline "others" is exhausted,  a newline is
  175.         needed because a newline was not included in the  definition
  176.         above.   A  single "putc" is then executed which outputs the
  177.         "\n" character to return the carriage and do a linefeed.
  178.  
  179.              When  the outer loop has been executed ten  times,  the
  180.         program  closes the file and terminates.   Compile  and  run
  181.         this  program but once again there will be no output to  the
  182.         monitor.
  183.  
  184.              Following  execution  of the program,  "type" the  file
  185.         named  TENLINES.TXT and you will see that the 10  new  lines
  186.         were  added to the end of the 10 that already  existed.   If
  187.         you run it again,  yet another 10 lines will be added.  Once
  188.  
  189.  
  190.                                    Page 72
  191.  
  192.  
  193.  
  194.  
  195.  
  196.  
  197.  
  198.  
  199.  
  200.                        Chapter 10 - File Input/Output
  201.  
  202.  
  203.         again,  do  not  erase  this file because we are  still  not
  204.         finished with it.
  205.  
  206.                                READING A FILE
  207.  
  208.              Load  the file named READCHAR.C and display it on  your
  209.         monitor. This is our first program to read a file.
  210.  
  211.              This program begins with the familiar  "include",  some
  212.         data  definitions,  and  the  file opening  statement  which
  213.         should  require no explanation except for the fact  that  an
  214.         "r"  is  used  here because we want to  read  it.   In  this
  215.         program,  we  check to see that the file exists,  and if  it
  216.         does,  we  execute  the  main body of the  program.   If  it
  217.         doesn't,  we print a message and quit.  If the file does not
  218.         exist,  the system will set the pointer equal to NULL  which
  219.         we can test.
  220.  
  221.              The  main body of the program is one "do while" loop in
  222.         which a single character is read from the file and output to
  223.         the monitor until an EOF (end of file) is detected from  the
  224.         input  file.   The  file is then closed and the  program  is
  225.         terminated.
  226.  
  227.                          CAUTION  CAUTION  CAUTION
  228.  
  229.              At  this  point, we have the potential for one  of  the
  230.         most  common and most perplexing problems of programming  in
  231.         C.   The  variable returned from the "getc"  function  is  a
  232.         character, so we can use a "char" variable for this purpose.
  233.         There is a problem that could develop here if we happened to
  234.         use  an "unsigned char" however, because C returns  a  minus
  235.         one for an EOF which an "unsigned char" type variable is not
  236.         capable of containing.  An "unsigned char" type variable can
  237.         only have the values of zero to 255, so it will return a 255
  238.         for a minus one.  This is a very frustrating problem to  try
  239.         to  find.   The  program can never find  the  EOF  and  will
  240.         therefore  never  terminate  the  loop.   This  is  easy  to
  241.         prevent,  always  use  an "char" type variable  for  use  in
  242.         returning an EOF.
  243.  
  244.              There is another problem with this program but we  will
  245.         worry  about it when we get to the next program and solve it
  246.         with the one following that.
  247.  
  248.              After  you  compile  and  run  this  program  and   are
  249.         satisfied  with the results,  it would be a good exercise to
  250.         change the name of "TENLINES.TXT" and run the program  again
  251.         to see that the NULL test actually works as stated.  Be sure
  252.         to  change  the name back because we are still not  finished
  253.         with "TENLINES.TXT".
  254.  
  255.  
  256.                                    Page 73
  257.  
  258.  
  259.  
  260.  
  261.  
  262.  
  263.  
  264.  
  265.  
  266.                        Chapter 10 - File Input/Output
  267.  
  268.  
  269.  
  270.                           READING A WORD AT A TIME
  271.  
  272.              Load  and  display  the file named  READTEXT.C  for  an
  273.         example of how to read a word at a time.
  274.  
  275.              This  program  is nearly identical as the  last  except
  276.         that  this program uses the "fscanf" function to read  in  a
  277.         string  at  a  time.   Because the "fscanf"  function  stops
  278.         reading  when it finds a space or a  newline  character,  it
  279.         will read a word at a time, and display the results one word
  280.         to  a line.   You will see this when you compile and run it,
  281.         but first we must examine a programming problem.
  282.  
  283.                              THIS IS A PROBLEM
  284.  
  285.              Inspection of the program will reveal that when we read
  286.         data in and detect the EOF, we print out something before we
  287.         check  for the EOF resulting in an extra line  of  printout.
  288.         What  we usually print out is the same thing printed on  the
  289.         prior  pass  through  the loop because it is  still  in  the
  290.         buffer "oneword".  We therefore must check for EOF before we
  291.         execute  the  "printf"  function.   This has  been  done  in
  292.         READGOOD.C,  which  you will shortly examine,  compile,  and
  293.         execute.
  294.  
  295.              Compile  and execute the original program we have  been
  296.         studying, READTEXT.C and observe the output.  If you haven't
  297.         changed  TENLINES.TXT you will end up with "Additional"  and
  298.         "lines."  on  two  separate lines  with  an  extra  "lines."
  299.         displayed  because of the "printf" before checking for  EOF.
  300.         Note  that some compilers apparently clear the buffer  after
  301.         printing  so you may get an extra blank line instead of  two
  302.         lines with "lines." on them.
  303.  
  304.              Compile  and  execute READGOOD.C and observe  that  the
  305.         extra  "lines." does not get displayed because of the  extra
  306.         check for the EOF in the middle of the loop.   This was also
  307.         the problem referred to when we looked at READCHAR.C,  but I
  308.         chose  not  to expound on it there because the error in  the
  309.         output was not so obvious.
  310.  
  311.                         FINALLY, WE READ A FULL LINE
  312.  
  313.              Load and display the file READLINE.C for an example  of
  314.         reading  a complete line.   This program is very similar  to
  315.         those  we have been studying except that we read a  complete
  316.         line.
  317.  
  318.              We  are  using "fgets" which reads in an  entire  line,
  319.         including  the newline character into a buffer.   The buffer
  320.  
  321.  
  322.                                    Page 74
  323.  
  324.  
  325.  
  326.  
  327.  
  328.  
  329.  
  330.  
  331.  
  332.                        Chapter 10 - File Input/Output
  333.  
  334.  
  335.         to be read into is the first argument in the function  call,
  336.         and  the maximum number of characters to read is the  second
  337.         argument,  followed by the file pointer.  This function will
  338.         read  characters into the input buffer until it either finds
  339.         a  newline  character,  or it reads the  maximum  number  of
  340.         characters  allowed minus one.   It leaves one character for
  341.         the end of string NULL character.   In addition, if it finds
  342.         an  EOF,  it will return a value of NULL.   In our  example,
  343.         when the EOF is found,  the pointer "c" will be assigned the
  344.         value  of NULL.   NULL is defined as zero in your  "stdio.h"
  345.         file.
  346.  
  347.              When  we find that "c" has been assigned the  value  of
  348.         NULL,  we can stop processing data, but we must check before
  349.         we print just like in the last program.
  350.  
  351.              Last of course, we close the file.
  352.  
  353.                        HOW TO USE A VARIABLE FILENAME
  354.  
  355.              Load  and display the file ANYFILE.C for an example  of
  356.         reading  from any file.   This program asks the user for the
  357.         filename desired,  reads in the filename and opens that file
  358.         for reading.   The entire file is then read and displayed on
  359.         the   monitor.    It  should  pose  no  problems   to   your
  360.         understanding so no additional comments will be made.
  361.  
  362.              Compile  and  run  this program.   When it  requests  a
  363.         filename,  enter  the  name and extension of any  text  file
  364.         available, even one of the example C programs.
  365.  
  366.                               HOW DO WE PRINT?
  367.  
  368.              Load  the  last example file in this chapter,  the  one
  369.         named  PRINTDAT.C  for an example of  how  to  print.   This
  370.         program  should not present any surprises to you so we  will
  371.         move very quickly through it.
  372.  
  373.              Once  again,  we  open TENLINES.TXT for reading and  we
  374.         open PRN for writing.  Printing is identical to writing data
  375.         to  a disk file except that we use a standard name  for  the
  376.         filename.  Most C compilers use the reserved  "filename"  of
  377.         "PRN" that instructs the compiler to send the output to  the
  378.         printer.   There are other names that are used  occationally
  379.         such  as "LPT", "LPT1", or "LPT2".  Check the  documentation
  380.         for your particular compiler.
  381.  
  382.              Some  of  the newest compilers use  a  predefined  file
  383.         pointer  such as "stdprn" for the print file.   Once  again,
  384.         check your documentation.
  385.  
  386.  
  387.  
  388.                                    Page 75
  389.  
  390.  
  391.  
  392.  
  393.  
  394.  
  395.  
  396.  
  397.  
  398.                        Chapter 10 - File Input/Output
  399.  
  400.  
  401.              The  program is simply a loop in which a  character  is
  402.         read, and if it is not the EOF, it is displayed and printed.
  403.         When the EOF is found, the input file and the printer output
  404.         files are both closed.  Note that good programming  practice
  405.         would include checking both file pointers to assure that the
  406.         files were opened properly.
  407.  
  408.              You can now erase TENLINES.TXT from your disk.  We will
  409.         not be using it in any of the later chapters.
  410.  
  411.  
  412.         PROGRAMMING EXERCISES
  413.  
  414.         1.   Write a program  that will prompt for a filename for  a
  415.              read file,  prompt for a filename for a write file, and
  416.              open both plus a file to the printer. Enter a loop that
  417.              will read a character,  and output it to the file,  the
  418.              printer, and the monitor. Stop at EOF.
  419.  
  420.         2.   Prompt for a  filename to read. Read the file a line at
  421.              a time and display it on the monitor with line numbers.
  422.  
  423.         3.   Modify ANYFIE.C to test if the file exists and print  a
  424.              message  if it doesn't.  Use a method similar  to  that
  425.              used in READCHAR.C.
  426.  
  427.  
  428.  
  429.  
  430.  
  431.  
  432.  
  433.  
  434.  
  435.  
  436.  
  437.  
  438.  
  439.  
  440.  
  441.  
  442.  
  443.  
  444.  
  445.  
  446.  
  447.  
  448.  
  449.  
  450.  
  451.  
  452.  
  453.  
  454.                                    Page 76
  455.